<template>
	<div ref="chartRef" :style="{ width, height }"></div>
</template>

<script setup name="chart">
import { onMounted, ref, watchEffect } from 'vue';
import * as echarts from 'echarts';

import { useResizeObserver, useVModel } from '@vueuse/core';

const props = defineProps({
	modelValue: {
		type: Object,
		default: {},
	},
	height: {
		type: String,
		default: '100%',
	},
	width: {
		type: String,
		default: '100%',
	},
});

const emit = defineEmits(['update:modelValue']);
const data = useVModel(props, 'modelValue', emit);
const chartRef = ref();
let chart = ref();

const initChart = () => {
	if (chartRef.value) {
		chart = echarts.init(chartRef.value);
		chart.setOption(data.value);
	}
};

// 定义一个函数来处理尺寸变化
const handleResize = () => {
	if (chart) {
		setTimeout(() => {
			chart.resize();
		}, 100);
	}
};

const setOption = (option) => {
	if (chartRef.value) {
		chart = echarts.init(chartRef.value);
		chart.setOption(option);
	}
};

watchEffect(() => {
	setOption(data.value);
});
onMounted(() => {
	initChart();
	// 监听窗口大小变化
	if (chartRef.value) {
		useResizeObserver(chartRef.value.parentNode, handleResize);
	}
});
const getChart = () => {
	return chart;
};
defineExpose({
	getChart,
	setOption,
});
</script>
